<?php

namespace App\Http\Controllers\Api;

use App\Socialite;
use App\User;
use App\UserCard;
use Carbon\Carbon;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class WechatController extends BaseController
{
    protected $wechat;
    function __construct()
    {
        $this->wechat = app('wechat.official_account');
    }

    public function officialAccountLogin(Request $request)
    {
        // 拿到授权用户资料
        $user = session('wechat.oauth_user.default');
        if ($user) {
            $socialite = Socialite::getByDriverAndOpenId('wechat', $user->getId());
            // 已绑定用户
            if ($socialite && $socialite->user) {
                return $this->_login($socialite->user);
            }
            return $this->_register($user, $request, $socialite);
        }
        return response(['message' => '授权失败'], 400);
    }

    /**
     * 用户注册或绑定
     *
     * @param $user
     * @param Request $request
     * @param Socialite|null $socialite
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    protected function _register($user, Request $request, Socialite $socialite = null)
    {
        $openId   = $user->getId();           // 对应微信的 OPENID
        $nickName = $user->getNickname();     // 对应微信的 nickname
        $avatar   = $user->getAvatar();       // 头像
        $authInfo = $user->getOriginal();     // 原始API返回的结果
        $parentId = 1;

        // ?from=userId, 代表用户同过发送链接的方式推荐。
        if ($request->from) {
            $fromUser = User::find($request->from);
            if ($fromUser) {
                $parentId = $fromUser->id;
            }
        }

        // 通过扫描带参数的二维码注册的用户
        $parent = null;
        if ($socialite && $socialite->from) {
            $parent = Socialite::getByDriverAndOpenId('wechat', $socialite->from);
            if ($parent) {
                $parentId = $parent->user_id;
            }
        }

        $registerUser = User::create([
            'name' => $nickName,
            'parent_id' => $parentId,
            'account' => $this->_generateUserAccount(),
            'avatar' => $avatar,
            'password' => bcrypt(str_random(10))
        ]);

        if (!$socialite) {
            // 创建关联
            Socialite::createOne($registerUser->id, 'wechat', $openId, $authInfo);
        } else {
            if ($parent && $parent->user) {
                $message = new Text($registerUser->name . '通过扫描二维码加入了你的团队！');
                $this->wechat->customer_service->message($message)->to($parent->open_id)->send();
            }
            $socialite->user_id = $registerUser->id;
            $socialite->save();
        }
        return $this->_login($registerUser);
    }
    protected function _login(User $user)
    {
        $access_token = $user->createToken('wechat' . '_' . $user->id . '_' . date('YmdHis'))->accessToken;
        return redirect(env('WECHAT_URL') . '/?#login?access_token='. $access_token);
    }

    protected function _generateUserAccount() {
        $account = null;
        // 保证不会有重复
        while(true){
            $account = 'u_'.rand(1000000,9999999);
            $sn = User::where("account", $account)->first();
            if(!$sn)
                break;
        }
        return $account;
    }

    public function jssdkConfig(Request $request)
    {
        $this->wechat->jssdk->setUrl('http://m.tnswh.com/?');
        $config = $this->wechat->jssdk->buildConfig(['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareQZone', 'onMenuShareWeibo'], false, false, true);
        return $config;
    }

    public function qrcode(Request $request)
    {
        $type = $request->get("type") ? $request->get("type") : 1;
        if ($request->from && $request->from != Auth::id()) {
            $card = UserCard::where('user_id', $request->from)
                ->where('type', $type)
                ->latest()
                ->first();
            if ($card) {
                return asset('storage/'.$card->path);
            } else {
                return response(['message' => '连接已失效'], 400);
            }
        }

        $card = UserCard::where('user_id', Auth::id())
            ->where('type', $type)
            ->where('expired_at', '>', Carbon::now())
            ->latest()
            ->first();
        if ($card) {
            return asset('storage/'.$card->path);
        }
        $socialite = Socialite::where('user_id', Auth::id())->where('driver', 'wechat')->first();
        if ($socialite) {
            $res = $this->wechat->qrcode->temporary('distribution_'.$socialite->open_id, 30 * 24 * 3600);
            if ($type == 1) {
                $qrcode = QrCode::format('png')->margin(0)->size(480)->generate($res['url']);
                $avatar = Auth::user()->avatar;
                if (strpos($avatar, 'http') === false) {
                    $avatar = 'storage/' . $avatar;
                } else {
                    $client = new Client();
                    $avatar = $client->get($avatar);
                    $avatar = $avatar->getBody()->getContents();
                }
                $avatar = Image::make($avatar)->fit(130);
                $path = 'images/qrcode/' . date('Ym/') . md5(time() . str_random(20)) . '.jpg';
                $image = Image::make('images/share.jpg');
                $image->insert($qrcode, 'top-left', 290, 320);
                $image->insert($avatar, 'bottom-left', 120, 210);
                $image->text('你的好朋友', 279, 1550, function ($font) {
                    $font->file('fonts/bmyh.ttf');
                    $font->size(50);
                });
                $image->text(Auth::user()->name . '，推荐你关注！', 279, 1620, function ($font) {
                    $font->file('fonts/bmyh.ttf');
                    $font->size(50);
                });
            } else {
                if (!Auth::user()->hasRole('Teacher')) {
                    return response(['message' => 'Teacher only'], 400);
                }
                $qrcode = QrCode::format('png')->margin(0)->size(120)->generate($res['url']);
                $path = 'images/qrcode/' . date('Ym/') . md5(time() . str_random(20)) . '.jpg';
                $image = Image::make('images/card.jpg');
                $image->insert($qrcode, 'top-left', 30, 140);
                $textArr = $this->ch2arr(Auth::user()->name.'老师');
                foreach ($textArr as $k => $v) {
                    $top = 120 + $k * 50;
                    $image->text($v, 200, $top, function ($font) {
                        $font->file('fonts/bmyh.ttf');
                        $font->size(36);
                        $font->color('#4e06d2');
                    });
                }
            }
           // $image->save('storage/' . $path);
            Storage::disk('public')->put($path, $image->stream(), 'public');
            $card = UserCard::create([
                'user_id' => Auth::id(),
                'path' => $path,
                'type' => $type,
                'expired_at' => Carbon::now()->addDays(15),
            ]);
            return asset('storage/' . $card->path);
        }
        return response(['message'  => '未绑定微信账号'], 400);
    }

    public function wechat()
    {
        $app = $this->wechat;
        $app->server->push(function ($message) use ($app) {
            Log::info($message);
            // $message['FromUserName']  用户的 openid
            // $message['MsgType']  消息类型：event, text....
            // 处理带参数的二维码扫描关注事件
            if ($message['EventKey']) {
                // 'EventKey' => 'qrscene_distribution_1',
                $keyArr = explode('_', $message['EventKey'], 3);
                // 带参数的二维码推广
                if (count($keyArr) == 3 && $keyArr[0] == 'qrscene' && $keyArr['1'] == 'distribution') {
                    $distributionUser = Socialite::getByDriverAndOpenId('wechat', $keyArr[2]);
                    $registered = Socialite::getByDriverAndOpenId('wechat', $message['FromUserName']);
                    // 用户未注册
                    if (!$registered) {
                        // 存在推荐用户
                        if ($distributionUser && $distributionUser->user) {
                            Socialite::createOne(0, 'wechat', $message['FromUserName'], null, $distributionUser->open_id);
                        }
                    }
                }
            }
            return "您好！欢迎您来到天南山文化，通过底部菜单你可以便捷的了解我们。";
        });
        return $app->server->serve();
    }

    protected  function ch2arr($str)
    {
        $length = mb_strlen($str, 'utf-8');
        $array = [];
        for ($i=0; $i<$length; $i++)
            $array[] = mb_substr($str, $i, 1, 'utf-8');
        return $array;
    }

    public function menu()
    {
        //$this->wechat->menu->delete(); // 全部
        // return $this->wechat->menu->list();
        // return $this->wechat->menu->current();
        $url = 'http://m.tnswh.com/?#/';
        $buttons = [
            [
                "name"       => "天南山文化",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "爱心众筹",
                        "url"  => $url . "donation"
                    ],
                    [
                        "type" => "view",
                        "name" => "天南山动态",
                        "url"  => $url . "posts?category=3"
                    ],
                    [
                        "type" => "view",
                        "name" => "天南山读书会",
                        "url"  => $url . "posts?category=2"
                    ],
                    [
                        "type" => "view",
                        "name" => "天南山商城",
                        "url" => $url . "products"
                    ],
                ],
            ],
            [
                "type" => "view",
                "name" => "精彩课程",
                "url"  => $url
            ],
            [
                "name" => "管理中心",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "必读公告",
                        "url"  => $url . "posts/3"
                    ],
                    [
                        "type" => "view",
                        "name" => "个人中心",
                        "url"  => $url . "user"
                    ],
                ]
            ],
        ];
        $rs = $this->wechat->menu->create($buttons);
        return ($rs);
    }
}